import pymysql
from ..database import connect_to_database, close_database_connection
from datetime import datetime, timedelta
from jose import jwt
from config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES, ADMIN_CREDENTIALS



def create_access_token(user_id: str):
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode = {"sub": user_id, "exp": expire}
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

async def selectUserByName(uUserName, uPassword):
    # 管理员身份验证
    if uUserName in ADMIN_CREDENTIALS:
        if ADMIN_CREDENTIALS[uUserName] == uPassword:
            access_token = create_access_token(user_id=uUserName)
            return {"access_token": access_token, "token_type": "bearer", "is_admin": True}

    db, ssh_tunnel = connect_to_database()
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
    sql1 = "SELECT * FROM `user` WHERE id = %s AND user_pass = %s"
    try:
        cursor.execute(sql1, (uUserName, uPassword))
        data1 = cursor.fetchone()  # 获取单个用户数据
        db.commit()
    except Exception as e:
        print(e)
        data1 = None
        db.rollback()
    cursor.close()
    close_database_connection(db, ssh_tunnel)

    if data1:
        # 用户登录成功，生成 Token
        access_token = create_access_token(user_id=data1["id"])
        return {"access_token": access_token, "token_type": "bearer", "is_admin": False}
    else:
        return None
